package com.webflux.advice;

import com.webflux.exceptions.CheckException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;

/**
 * 异常处理切面
 *
 * @author 晓风轻
 *
 */
@ControllerAdvice
public class CheckAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleBindException(MethodArgumentNotValidException e) {
        ResponseEntity<String> entity = new ResponseEntity<>(toStr(e), HttpStatus.BAD_REQUEST);
        return entity;
    }

    @ExceptionHandler(CheckException.class)
    public ResponseEntity<String> handleCheckException(CheckException e) {
        ResponseEntity<String> entity = new ResponseEntity<>(toStr(e), HttpStatus.BAD_REQUEST);
        return entity;
    }

    private String toStr(CheckException e) {
        return e.getFieldName() + ":错误的值，" + e.getFieldValue();
    }

    /**
     * 把校验异常转换为字符串
     * 原本的WebExchangeBindException不行
     * @param ex
     * @return
     */
    private String toStr(MethodArgumentNotValidException ex) {
        String reduce = ex.getBindingResult().getFieldErrors().stream()
                .map(e -> e.getField() + ":" + e.getDefaultMessage())
                .reduce("", (s1, s2) -> s1 + "\n" + s2);
        return reduce;
    }

}
